package com.fourth.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fourth.entity.Cart;
import com.fourth.entity.Pay;
import com.fourth.entity.User;
import com.fourth.dao.CartMapper;
import com.fourth.dao.PayMapper;
import com.fourth.dao.UserMapper;
import com.fourth.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;
    @Resource
    CartMapper cartMapper;
    @Resource
    PayMapper payMapper;
    @Override
    public List<User> selectAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public User login(String uName, String uPassword) {
        return userMapper.selectUserByNameAndPass(uName,uPassword);
    }

    @Override
    public String checkUsername(String uName) {
        if(uName==""){
            return "false";
        }
        //判断首字母是否以字母开头
        String normHead="^[a-zA-Z].*";
        boolean matchesHead = uName.matches(normHead);

        //判断是否有非法字符，有返回true
        String normBody="^.*(?=exe|insert|create|[!@#$%^&*|()（）：；:;'“”、？?.,]).*$";
//        String normBody="[`~!@#$%^&*()+=|{}':;',.<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        boolean matchesBody = uName.matches(normBody);

        if(matchesHead==true&matchesBody==false){
            return  "true";
        }else {
            return  "false";
        }
    }

    @Override
    public String selectUserByuName(String uName) {

        User user = userMapper.selectUserByUName(uName);

        if(user!=null){
            return "exist";
        }else {
            return "inexistence";
        }
    }

    @Override
    public String checkPassword(String password, String repassword) {

        if(password==""||repassword==""){
            return "passwordUnable";
        }

        boolean equals = password.equals(repassword);
        if(equals){
            return "passwordUsable";
        }else {
            return "passwordUnable";
        }
    }

    @Override
    public String checkEmail(String email) {

        if(email==""){
            return "emailUnable";
        }

        String emailNorm="\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

        boolean matches = email.matches(emailNorm);

        if(matches){
            return "emailUsable";
        }else {
            return "emailUnable";
        }
    }

    @Override
    public String register(User user, String repassword) {

        String checkUsername = checkUsername(user.getUName());
        String selectUserByuName = selectUserByuName(user.getUName());
        String checkPassword = checkPassword(user.getUPassword(), repassword);
        String checkEmail = checkEmail(user.getUEmail());

        if(checkUsername=="true"&&selectUserByuName=="inexistence"&&checkPassword=="passwordUsable"&&checkEmail=="emailUsable"){
            Date now =new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateFormat.format(now);

            BigDecimal uBalance = new BigDecimal(1000000.00);

            User user1=new User();
            user1.setUName(user.getUName());
            user1.setUPassword(user.getUPassword());
            user1.setUEmail(user.getUEmail());
            user1.setUSex(user.getUSex());
            user1.setUStatus(1);
            user1.setUPhone(user.getUPhone());
            user1.setURegisterDate(now);
            user1.setUBalance(uBalance);

            int i = userMapper.insertIntoUser(user1);
            if(i==1){
                return "registerSuccess";
            }
        }
        return "registerDefeat";
    }

    /**
     * 检查电话是否符合规范
     * 第一位： 1
     * 第二位： 3～9
     * 第三到第十一位只要是数字就行
     * @param phone
     * @return
     */
    @Override
    public String checkPhone(String phone) {

        if(phone==""){
            return "phoneUnable";
        }

        String normPhone="1[3-9]\\d{9}";
        boolean matches = phone.matches(normPhone);

        if(matches){
            return "phoneUsable";
        }else {
            return "phoneUnable";
        }
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @Override
    public String dateCodeSend(String phone) {

        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "50000");
        System.setProperty("sun.net.client.defaultReadTimeout", "50000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //替换成你的AK
        final String accessKeyId = "LTAI4GJiXa75N8nUEV9uW2FH";//你的accessKeyId,参考本文档步骤2
//        final String accessKeyId = "LTAI4G3n6vBcHaXLay5XjgNp";//你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "XZBlMBxaa3FsuxblVtgDbo4olcmPs3";//你的accessKeySecret，参考本文档步骤2
//        final String accessKeySecret = "ATIEa1bhzQBQxPuhuVc2WM4BhO3tcl";//你的accessKeySecret，参考本文档步骤2
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {

            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("爱笑的不辜负你");
//        request.setSignName("千锋商城购物车项目");
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode("SMS_192530814");
//        request.setTemplateCode("SMS_192530095");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");

        int random = (int)(Math.random()*1000000);

        String strRandom=Integer.toString(random);

        request.setTemplateParam("{\"code\":"+strRandom+"}");
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId(strRandom);
        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")){
            return strRandom+"-"+"ok";
        }else {
            return strRandom+"-"+"false";
        }

    }

    @Override
    public String mergeCartDate(ArrayList<Cart> myCart, int uId) {

        if(myCart==null){
            return "购物车为空";
        }else {
            for (Cart cart : myCart) {
                String goodsId = cart.getGoodId();
                Cart cart2 = cartMapper.selectCartByGoodIdAndUId(goodsId, uId);
                //根据goodId与uId查询，如果无记录则直接插入数据，有记录则将两条数据num相加
                if(cart2==null){
                    Cart cart1=new Cart();
                    cart1.setGoodId(goodsId);
                    cart1.setUId(uId);
                    cart1.setNum(cart.getNum());
                    int i1 = cartMapper.insertMoreCartItem(cart1);
                }else {
                    int i2 = cartMapper.updateMoreGoodsNum(cart.getNum(), goodsId, uId);
                }
            }
        }
        return "合并完成";
    }

    @Override
//    @Transactional
    public int insertPayRecord(Pay pay) {
        int i = payMapper.insertPayRecord(pay);
        return i;
    }
}
